package concurrent

import (
	"sync"
	"fmt"
	"time"
)

func Hello(i int) {
	println("[", i, "] hello marion")
}

// 1. 多个goroutine正常执行顺序
func MultiGo1() {
	// 1. 测试多个goroutine执行顺序
	for i := 0; i < 10; i++ {
		println("i = ", i)
		go Hello(i)
	}

	println("multi go")
}

var wg sync.WaitGroup

func Hello2(i int) {
	defer wg.Done()
	println("[", i, "] hello marion")
}

// 2. 使用了sync.WaitGroup来实现goroutine的同步
func MultiGo2() {
	// 1. 测试多个goroutine执行顺序
	for i := 0; i < 10; i++ {
		println("i = ", i)
		wg.Add(1)
		go Hello2(i)
	}

	wg.Wait()
	println("multi go")
}

// 3. 主线程退出，其他任务是否执行？否
func MultiGo3() {
	// 协程
	go func() {
		i := 0
		for {
			i++
			fmt.Printf("new goroutine: i = %d\n", i)
			time.Sleep(time.Second)
		}
	}()

	// 主线程
	i := 0
	for {
		i++
		fmt.Printf("main goroutine: i = %d\n", i)
		time.Sleep(time.Second)
		if i == 2 {
			break
		}
	}
}
